<template>
    <el-card>
        <template #header>
            <h3>管理员账号信息</h3>
        </template>
        <el-button class="add" type="primary" @click="showAddWindow()">添加管理员账号</el-button>
        <!-- 搜索区域 -->
        <el-form inline>
            <!-- <el-form-item label="ID" style="width: 100px">
                <el-input v-model="params.user_id"></el-input>
            </el-form-item> -->
            <el-form-item label="账号" style="width: 200px">
                <el-input v-model="params.account"></el-input>
            </el-form-item>
            <el-form-item label="姓名" style="width: 200px">
                <el-input v-model="params.name"></el-input>
            </el-form-item>
            <!-- <el-form-item label="邮箱" style="width: 200px">
                <el-input v-model="params.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" style="width: 200px">
                <el-input v-model="params.phone"></el-input>
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" @click="searchAdmins()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格区域 -->
        <el-table :data="admin" border @sort-change="handleSortChange">
            <!-- <el-table-column type="index" width="54" label="序号" align="center" v-if="false"></el-table-column> -->
            <!-- <el-table-column label="ID" prop="user_id" align="center"></el-table-column> -->
            <el-table-column label="账号" prop="account" sortable="custom" align="center"></el-table-column>
            <el-table-column label="姓名" prop="name" sortable="custom" align="center"></el-table-column>
            <el-table-column label="邮箱" prop="email" sortable="custom" align="center"></el-table-column>
            <el-table-column label="电话" prop="phone" sortable="custom" align="center"></el-table-column>
            <el-table-column label="操作" width="280" align="center">
                <template #default="scope">
                    <el-button type="primary" @click="showEditWindow(scope.row)">编辑</el-button>
                    <!-- 重置密码确认气泡 -->
                    <el-popconfirm width="250" icon-color="#626AEF" title="确认重置该管理员账号的密码吗？">
                        <template #reference>
                            <el-button type="warning">重置密码</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                            <el-button size="small" @click.once="cancel">取消</el-button>
                            <el-button type="warning" size="small" @click.once="resetPassword(scope.row, confirm)">
                                确认
                            </el-button>
                        </template>
                    </el-popconfirm>
                    <!-- 删除确认气泡 -->
                    <el-popconfirm width="250" icon-color="#626AEF" title="确认删除该管理员账号吗？">
                        <template #reference>
                            <el-button type="danger">删除</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                            <el-button size="small" @click.once="cancel">取消</el-button>
                            <el-button type="danger" size="small" @click.once="deleteAdmin(scope.row, confirm)">
                                确认
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 管理员账号信息编辑弹窗 -->
    <el-dialog v-model="showEdit" title="管理员账号信息" width="500" @close="closeWindow">
        <el-form :model="curAdmin" label-width="120px" :rules="rules" ref="curAdminForm">
            <!-- 上传头像 -->
            <el-form-item label="头像" prop="avatar" v-show="!showAdd">
                <el-upload class="avatar-uploader" action="http://127.0.0.1:8082/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <el-avatar v-if="curAdmin.user_img" shape="circle" :size="150" :fit="'cover'"
                        :src="curAdmin.user_img" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="账号" prop="account">
                <el-input v-model="curAdmin.account" v-if="showAdd"></el-input>
                <el-input v-model="curAdmin.account" v-else disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="curAdmin.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" v-show="!showAdd">
                <el-input v-model="curAdmin.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="curAdmin.phone"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-if="!showAdd" type="primary" @click="updateAdmin(curAdmin)">保存</el-button>
                <el-button v-if="showAdd" type="primary" @click="addAdmin(curAdmin)">添加</el-button>
                <el-button @click="showEdit = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { findAdminInfoAPI, adminInfoUpdateAPI } from '@/api/user';
import { addUserAPI, deleteUserAPI, resetPasswordAPI } from '@/api/user';
import { ElMessage } from 'element-plus';
export default {
    data() {
        return {
            params: {
                // 搜索关键词
                user_id: '',
                name: '',
                account: '',
                email: '',
                phone: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7
            },
            admin: [],
            showEdit: false,
            showAdd: false,
            curAdmin: {
                email: '',
                phone: ''
            },
            rulesEdit: {
                name: { required: true, message: '姓名不能为空', trigger: 'blur' },
                account: { required: true, message: '账号不能为空', trigger: 'blur' },
                email: [
                    { required: false, trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const emailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                            if (!this.showAdd && value !== '') {
                                if (emailRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的邮箱地址'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const phoneRegex = /^[0-9]{11}$/;
                            if (value !== '') {
                                if (phoneRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的手机号'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            rulesAdd: {
                name: { required: true, message: '姓名不能为空', trigger: 'blur' },
                account: { required: true, message: '账号不能为空', trigger: 'blur' },
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const phoneRegex = /^[0-9]{11}$/;
                            if (value !== '') {
                                if (phoneRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的手机号'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            rules: {}
        }
    },
    methods: {
        loadAdminInfoList() {
            findAdminInfoAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.admin = resp.data.datas;
                    this.params.total = resp.data.total;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        searchAdmins() {
            this.loadAdminInfoList();
        },
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadAdminInfoList();
        },
        // 图片上传成功之后回调函数
        handleAvatarSuccess(response) {
            this.curAdmin.user_img = response;
        },
        showEditWindow(row) {
            this.curAdmin = JSON.parse(JSON.stringify(row));
            this.showEdit = true;
            this.rules = this.rulesEdit;
        },
        updateAdmin(row) {
            this.$refs.curAdminForm.validate((val) => {
                if (val) {
                    adminInfoUpdateAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            if (row.user_id == JSON.parse(sessionStorage.getItem('user')).user_id) {
                                // 记录原头像
                                let oldAvatar = JSON.parse(sessionStorage.getItem('user')).user_img;
                                // 更新session
                                sessionStorage.setItem('user', JSON.stringify(resp.data.data));
                                sessionStorage.setItem('message', resp.data.message);
                                if (oldAvatar != row.user_img) {
                                    // 刷新页面
                                    location.reload();
                                }
                            }
                            this.loadAdminInfoList();
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
            this.showEdit = false
        },
        resetPassword(row, confirm) {
            resetPasswordAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            confirm();
        },
        deleteAdmin(row, confirm) {
            deleteUserAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    this.loadAdminInfoList();
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            confirm();
        },
        showAddWindow() {
            this.curAdmin = {};
            this.showEdit = true;
            this.showAdd = true;
            this.rules = this.rulesAdd;
        },
        addAdmin(row) {
            row.role = 2;
            this.$refs.curAdminForm.validate((val) => {
                if (val) {
                    addUserAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadAdminInfoList();
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
            this.showEdit = false;
            this.showAdd = false;
        },
        closeWindow() {
            this.loadAdminInfoList();
            this.showEdit = false;
            this.showAdd = false;
        },
        handleSortChange({ prop, order }) {
            if (order) {
                // 根据 prop 和 order 进行排序
                this.params.sortProp = prop;
                this.params.sortOrder = order === 'ascending' ? 'asc' : 'desc';
                this.loadAdminInfoList();
            } else {
                // 清除排序
                delete this.params.sortProp;
                delete this.params.sortOrder;
                this.loadAdminInfoList();
            }
        }
    },
    created() {
        this.loadAdminInfoList();
    },
    mounted() {
        // 页面加载时检查并显示消息
        const message = sessionStorage.getItem('message');
        if (message) {
            ElMessage.success(message);
            // 清除消息
            sessionStorage.removeItem('message');
        }
    },
}
</script>

<style scoped>
.el-pagination {
    margin: 20px 0 0 450px;
    align-items: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.add {
    position: relative;
    top: -10px;
}
</style>